package com.iptv.grape.net;

import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.iptv.grape.RunTimeApplication;
import com.iptv.grape.bu.AppConfig;
import com.iptv.grape.bu.GrapeContext;
import com.iptv.grape.domain.Channel;
import com.iptv.grape.domain.ChannelBill;
import com.iptv.grape.domain.ChannelType;
import com.iptv.grape.domain.UserInfo;
import com.iptv.grape.event.EventArgs;
import com.iptv.grape.net.Entity.*;
import com.iptv.grape.util.AppLog;
import com.iptv.grape.util.CommUtil;
import com.iptv.grape.util.ReadJsonFile;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NetworkService {
    private static NetworkService _instance;
    private OkHttpClient client = new OkHttpClient();
    //private Handler mDelivery;
    //private Gson mGson;
    public static final String StartUpServiceBaseUrl = "http://117.158.207.135:3100";
    public static final String LiveServiceBaseUrl = "http://117.158.207.135:3300";
    public static final String AAAServiceBaseUrl = "http://117.158.207.135:3200";
    public static final String TTLSerbiceBaseUrl = "http://117.158.207.135:3400";
    public static final String VodSerbiceBaseUrl = "http://117.158.207.135:3600";
    // 事件类型
    public static final String EventType = "NetworkService";
    public static final MediaType RequestMediaType
            = MediaType.get("application/json; charset=utf-8");

    // 单例
    public static NetworkService getInstance() {
        if (_instance == null) {
            _instance = new NetworkService();
        }
        return _instance;
    }

    // 获取开机启动图
    public void getAppRunimg() {
        String serviceUrl = StartUpServiceBaseUrl + "/startUp/runimg";
        Request request = BuildRequest(serviceUrl);
        client.newCall(request).enqueue(new Callback() {
                                            @Override
                                            public void onFailure(Call call, final IOException e) {
                                                // 暂时不处理 直接发送事件 但是没有接收参数
                                                EventBus.getDefault().post(new EventArgs("getAppRunimg", EventType));
                                            }

                                            @Override
                                            public void onResponse(Call call, Response response) throws IOException {
                                                String json = response.body().string();
                                                // 解析返回值
                                                RunImgResult runImgResult = RunImgResult.createForJson(json);

                                                if(runImgResult.getRtCode().equals("S")) {
                                                    // 存在启动图 则需要判断开机启动图的版本号是否一致
                                                    if (!runImgResult.getData().getVersion().equals(AppConfig.getAppConfig().getImgVersion())) {
                                                        // 如果不相等 下载图片
                                                        Bitmap bitmap = null;
                                                        try {
                                                            bitmap = Glide
                                                                    .with(RunTimeApplication.getCurApp().getApplicationContext())
                                                                    .asBitmap()//这一个必须加
                                                                    .load(runImgResult.getData().getImg())
                                                                    .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                                                                    .get();
                                                            // 写入文件
                                                            ReadJsonFile.writeImgToFile("runimg.jpg", bitmap);
                                                            AppConfig.getAppConfig().setImgVersion(runImgResult.getData().getVersion());
                                                            AppConfig.getAppConfig().serializeToFile();
                                                            AppLog.getCurLog().out("下载开机图片并保存开机图片版本号 = " + runImgResult.getData().getVersion());
                                                        } catch (Exception e) {
                                                            bitmap = null;
                                                        }
                                                    } else {
                                                        AppLog.getCurLog().out("开机图片版本号 = " + AppConfig.getAppConfig().getImgVersion());
                                                    }
                                                }
                                                // 引发事件
                                                EventBus.getDefault().post(new EventArgs("getAppRunimg", EventType, runImgResult, json));

                                            }
                                        }
        );
    }

    // 获取点播暂停时的备件广告图片
    public boolean getAppAdImag() {

        try{
            String serviceUrl = VodSerbiceBaseUrl + "/vod/adImage";
            Request request = BuildRequest(serviceUrl);
            final Call call = client.newCall(request);
            Response response = call.execute();
            String json = response.body().string();
            // 解析返回值
            RunImgResult runImgResult = RunImgResult.createForJson(json);
            Bitmap bitmap = null;
            if(runImgResult.getRtCode().equals("S")) {
                // 存在广告图片
                try {
                    bitmap = Glide
                            .with(RunTimeApplication.getCurApp().getApplicationContext())
                            .asBitmap()//这一个必须加
                            .load(runImgResult.getData().getImg())
                            .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                            .get();
                    // 写入文件
                    ReadJsonFile.writeImgToFile("adimg.jpg", bitmap);
//                    AppConfig.getAppConfig().setAdImageVar(runImgResult.getData().getVersion());
//                    AppConfig.getAppConfig().serializeToFile();
//                    AppLog.getCurLog().out("下载暂停的广告背景图并保存版本号 = " + runImgResult.getData().getVersion());
                } catch (Exception e) {
                    bitmap = null;
                }
            }
            return bitmap != null;
        }
        catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    // 获取频道分类列表
    public void getChannelTypeList() {
        String serviceUrl = LiveServiceBaseUrl + "/live/channelTypeList";
        Request request = BuildRequest(serviceUrl);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                // 暂时不处理 直接发送事件 但是没有接收参数
                EventBus.getDefault().post(new EventArgs("getChannelTypeList", EventType));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                // 解析返回值
                ChannelTypeResult channelTypeResult = ChannelTypeResult.createForJson(json);
                EventBus.getDefault().post(new EventArgs("getChannelTypeList", EventType, channelTypeResult, json));
            }
        });
    }

    // 同步获得频道分类列表
    public List<ChannelType> getChannelTypeListAsync() {
        try {
            String serviceUrl = LiveServiceBaseUrl + "/live/channelTypeList";
            Request request = BuildRequest(serviceUrl);
            final Call call = client.newCall(request);
            Response response = call.execute();
            String json = response.body().string();
            ChannelTypeResult channelTypeResult = ChannelTypeResult.createForJson(json);
            if (channelTypeResult.getRtCode().equals("S")) {
                return channelTypeResult.getData().getChannelTypeList();
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 获取频道列表
    public void getChannelList() {
        String serviceUrl = LiveServiceBaseUrl + "/live/channelList";
        Request request = BuildRequest(serviceUrl);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                // 暂时不处理 直接发送事件 但是没有接收参数
                EventBus.getDefault().post(new EventArgs("getChannelList", EventType));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                // 解析返回值
                ChannelResult result = ChannelResult.createForJson(json);
                EventBus.getDefault().post(new EventArgs("getChannelList", EventType, result, json));
            }
        });
    }

    // 同步获取频道列表
    public List<ChannelData> getChannelListAsync() {
        try {
            String serviceUrl = LiveServiceBaseUrl + "/live/channelList";
            Request request = BuildRequest(serviceUrl);
            final Call call = client.newCall(request);
            Response response = call.execute();
            String json = response.body().string();
            ChannelResult result = ChannelResult.createForJson(json);
            if (result.getRtCode().equals("S")) {
                return result.getData().getChannelList();
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    // 根据日期获得节目单
    public void getChannelListDetailsByDate(Date date){
        String serviceUrl = LiveServiceBaseUrl + "/live//channelDetailsByDate";
        Request request = BuildRequest(serviceUrl,"curDate", CommUtil.changeTime(date));
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                // 暂时不处理 直接发送事件 但是没有接收参数
                EventBus.getDefault().post(new EventArgs("getBillList", EventType));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                // 解析返回值
                ChannelDetailsResult result = ChannelDetailsResult.createForJson(json);
                EventBus.getDefault().post(new EventArgs("getBillList", EventType, result, json));
            }
        });
    }

    // 根据日期获得节目单
    public List<ChannelBillData> getChannelListDetailsByDateAsync(String dateString){
        try {
            String serviceUrl = LiveServiceBaseUrl + "/live/channelDetailsByDate";
            Request request = BuildRequest(serviceUrl,"curDate",dateString);
            final Call call = client.newCall(request);
            Response response = call.execute();
            String json = response.body().string();
            ChannelDetailsResult result = ChannelDetailsResult.createForJson(json);
            if (result.getRtCode().equals("S")) {
                return result.getData().getBillList();
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    // 根据频道ID和日期获得节目单
    public List<ChannelBillData> getChannelListDetails(String keyID,String dateString){
        try {
            String serviceUrl = LiveServiceBaseUrl + "/live/channelDetails";
            HashMap<String,String> map = UserInfo.curUserInfo().toMap();
            map.put("curDate",dateString);
            map.put("channelID",keyID);
            Request request = BuildRequest(serviceUrl,map);
            final Call call = client.newCall(request);
            Response response = call.execute();
            String json = response.body().string();
            ChannelDetailsResult result = ChannelDetailsResult.createForJson(json);
            if (result.getRtCode().equals("S")) {
                return result.getData().getBillList();
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }



    // 根据节目单名称获得相关推荐
    public List<RecommendData> getLiveRecommendData(){
        try {
            String serviceUrl = VodSerbiceBaseUrl + "/vod/recommendChannel";
            HashMap<String,String> map = UserInfo.curUserInfo().toMap();
            Channel channel = GrapeContext.curGrapeContext().getChannelDLinkList().getCurChannel();
            ChannelBill nowChannelBill = null;
            if(channel != null){
                nowChannelBill = channel.getCurChannelBill();
            }
            if(nowChannelBill != null){
                map.put("playbillName", nowChannelBill.getName());
            }
            else {
                map.put("playbillName", "");
            }
            Request request = BuildRequest(serviceUrl,map);
            final Call call = client.newCall(request);
            Response response = call.execute();
            String json = response.body().string();
            RecommendResult result = RecommendResult.createForJson(json);
            if (result.getRtCode().equals("S")) {
                return result.getData().getRecommendList();
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 发送心跳包(同步)
    public TTLResult sendTTLAsync(){
        try{
            String serviceUrl = TTLSerbiceBaseUrl + "/ttl/life";
            Request request = BuildRequest(serviceUrl);
            final Call call = client.newCall(request);
            Response response = call.execute();
            String json = response.body().string();
            // 解析返回值
            TTLResult result = TTLResult.CreateForJson(json);

            if (result.getRtCode().equals("S")) {
                return result;
            }
            return null;
        }
        catch (Exception e){
            return null;
        }
    }

    // 心跳包
    public void sendTTL() {
        String serviceUrl = TTLSerbiceBaseUrl + "/ttl/life";
        Request request = BuildRequest(serviceUrl);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                // 暂时不处理 直接发送事件 但是没有接收参数
                EventBus.getDefault().post(new EventArgs("TTL", EventType));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                // 解析返回值
                TTLResult result = TTLResult.CreateForJson(json);
                EventBus.getDefault().post(new EventArgs("TTL", EventType, result, json));
            }
        });
    }


    // 获取机顶盒配置列表
    public void getConfigList() {
        String serviceUrl = StartUpServiceBaseUrl + "/startUp/config";
        Request request = BuildRequest(serviceUrl);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                // 暂时不处理 直接发送事件 但是没有接收参数
                EventBus.getDefault().post(new EventArgs("getConfigList", EventType));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                // 解析返回值
                ConfigResult result = ConfigResult.createForJson(json);
                EventBus.getDefault().post(new EventArgs("getConfigList", EventType, result, json));
            }
        });
    }

    // 同步获取APP配置信息
    public List<ConfigData> getConfigListAsync(){
        try {
            String serviceUrl = StartUpServiceBaseUrl + "/startUp/config";
            Request request = BuildRequest(serviceUrl);
            final Call call = client.newCall(request);
            Response response = call.execute();
            String json = response.body().string();
            ConfigResult result = ConfigResult.createForJson(json);
            if (result.getRtCode().equals("S")) {
                return result.getData().getConfigList();
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 同步访问机顶盒AAA认证
    public LoginResult loginAsync() {
        try {
            String serviceUrl = AAAServiceBaseUrl + "/aaa/login";
            Request request = BuildRequest(serviceUrl);
            final Call call = client.newCall(request);
            Response response = call.execute();
            String json = response.body().string();
            LoginResult result = LoginResult.CreateForJson(json);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            AppLog.getCurLog().out(e.getMessage());
            return null;
        }
    }

    // 获取机顶盒AAA认证
    public void login() {
        String serviceUrl = AAAServiceBaseUrl + "/aaa/login";
        Request request = BuildRequest(serviceUrl);
        AppLog.getCurLog().out("NetworkService----onResponse");
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                EventBus.getDefault().post(new EventArgs("login", EventType));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                // 解析返回值

                LoginResult result = LoginResult.CreateForJson(json);
                EventBus.getDefault().post(new EventArgs("login", EventType, result, json));
            }
        });
    }
    // 获取机顶盒AAA认证
    public void login(OkCall callback) {
        if(!isNetworkConnected()){
            callback.error(0,"网络访问失败，请检查您的网络连接");
        }
        String serviceUrl = AAAServiceBaseUrl + "/aaa/login";
        AppLog.getCurLog().e("login===>>",serviceUrl);
        Request request = BuildRequest(serviceUrl);
        final Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                AppLog.getCurLog().e("login===>>",e.getMessage());
                callback.error(-1,e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                AppLog.getCurLog().e("login===>>",json);
                callback.success(json);
            }
        });
    }

    // 辅助函数 构建请求对象
    private Request BuildRequest(String serviceUrl) {
        String json = UserInfo.curUserInfo().toJson();
        RequestBody body = RequestBody.create(RequestMediaType, json);
        Request request = new Request.Builder()
                .url(serviceUrl)
                .post(body)
                .build();
        return request;
    }

    // 辅助函数 构建请求对象
    private Request BuildRequest(String serviceUrl,String key,String val) {
        HashMap<String,String> map = UserInfo.curUserInfo().toMap();
        map.put(key,val);
        Gson gson = new Gson();
        String json =gson.toJson(map);
        RequestBody body = RequestBody.create(RequestMediaType, json);
        Request request = new Request.Builder()
                .url(serviceUrl)
                .post(body)
                .build();
        return request;
    }

    // 辅助函数 构建请求对象
    private Request BuildRequest(String serviceUrl,HashMap<String,String> map) {

        Gson gson = new Gson();
        String json =gson.toJson(map);
        RequestBody body = RequestBody.create(RequestMediaType, json);
        Request request = new Request.Builder()
                .url(serviceUrl)
                .post(body)
                .build();
        return request;
    }


    public boolean isNetworkConnected() {

            ConnectivityManager mConnectivityManager = (ConnectivityManager) RunTimeApplication.getCurApp()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }

        return false;
    }

    public interface OkCall{
        void error(int code,String msg);
        void success(String value);
    }

}
